package com.tiancheng.trade.merchant.util;

import cn.hutool.core.date.DateUtil;
import com.tiancheng.trade.commom.core.utils.IdWorkerUtils;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 自定义生成唯一单号工具类
 */
@Component
public class IdGenerateUtil {
    @Resource
    private RedissonClient redissonClient;

    public String getProductCode() {
        String dateStr = DateUtil.format(LocalDateTime.now(), "yyyyMMddHHmmss");
        RAtomicLong rAtomicLong = redissonClient.getAtomicLong(dateStr);
        long incr = rAtomicLong.incrementAndGet();
        // 如果是当天第一个取号，就给key添加隔天失效时间
        if (incr == 1) {
            rAtomicLong.expireAsync(1, TimeUnit.DAYS);
        }
        return "PC" + dateStr + String.format("%05d", incr);
    }

    public String getBusinessCode(String businessName) {
        UUID uuid = UUID.nameUUIDFromBytes(businessName.getBytes(StandardCharsets.UTF_8));
        long mostSigBits = uuid.getMostSignificantBits();
        long leastSigBits = uuid.getLeastSignificantBits();
        // 移除 UUID 中的连字符
        String uuidStr = String.format("%016x%016x", mostSigBits, leastSigBits);
        final int hashCode = uuidStr.hashCode();
        return String.format("%07d", Math.abs(hashCode)) + "T";
    }

    /**
     * 获取终端号
     *
     * @return
     */
    public String getTermNo() {
        String uuid = IdWorkerUtils.getInstance().createUUID();
        // 移除 UUID 中的连字符
        final int hashCode = uuid.hashCode();
        return String.format("%08d", Math.abs(hashCode));
    }
}
